<?php

namespace App\Console\Commands\Transfer;

use App\Models\Ca\CustomerDisease;
use App\Models\Ca\Disease;
use App\Models\Ca\Visit;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CustomerCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'transfer:customer';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '迁移';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private $count = 0;

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '-1');
        DB::connection('S')->table('bs_booking')
            ->join('bs_customer', 'bs_customer.id', '=', 'bs_booking.customer_id')
            ->where('bs_booking.is_del', '=', 1)
            ->select('bs_booking')
            ->select(
                'bs_booking.id',
                'bs_booking.trust as consultation_type',
//                'bs_booking.cost_money',
                'bs_booking.hf_time',
//                'bs_booking.fb_time',
//                'bs_booking.medical_history',
                'bs_booking.creator_id',
                'bs_booking.consultation_way_id',
                'bs_booking.source_id',
                'bs_booking.custom_service_id',
                'bs_booking.yy_time',
                'bs_booking.yy_doctor_id',
//                'bs_booking.source_site',
//                'bs_booking.gm_words',
                'bs_booking.source_ip',
                'bs_booking.source_entry',
                'bs_booking.source_consulting_page',
                'bs_booking.source_search_keywords',
                'bs_booking.source_matching_keywords',
                'bs_booking.jz_doctor_id',
                'bs_booking.jz_time',
                'bs_booking.jz_guide_doctor_id',
                'bs_booking.status',
                'bs_booking.province_id',
                'bs_booking.city_id',
                'bs_booking.hospital_id',

                'bs_booking.swt',
                'bs_booking.medical_id',
                'bs_booking.remark',
                'bs_booking.disease_desc',
                'bs_booking.illness as disease_data',
                'bs_booking.stage',
                'bs_booking.create_time as created_at',
                'bs_booking.update_time as updated_at',
                'bs_customer.name',
                'bs_customer.gender',
                'bs_customer.phone',
                'bs_customer.qq',
                'bs_customer.weixin',
                'bs_customer.age',
                'bs_customer.mobile',
                'bs_customer.address',
                'bs_customer.zname as real_name',

            )
            ->selectRaw('case when bs_booking.jz_time>0 then FROM_UNIXTIME(bs_booking.jz_time) else null end jz_time')
            ->selectRaw('case when bs_booking.tady_yy_time>0 then FROM_UNIXTIME(bs_booking.tady_yy_time) else null end tady_yy_time')
            ->selectRaw('bs_booking.allot_status=1 as is_public')
            ->orderBy('bs_booking.id')
            ->chunk(1000, function ($data) {
                $cds = [];
                $addData = [];
                foreach ($data as $datum) {
                    $datum = (array)$datum;
                    if (empty($datum['hf_time'])) {
                        $datum['hf_time'] = null;
                    }
                    if ($datum['hf_time'] == 'javascript:;') {
                        $datum['hf_time'] = null;
                    }
                    if (empty($datum['phone'])) {
                        $datum['phone'] = '';
                    }
                    if (empty($datum['real_name'])) {
                        $datum['real_name'] = '';
                    }
                    if (empty($datum['weixin'])) {
                        $datum['weixin'] = '';
                    }
                    if (empty($datum['qq'])) {
                        $datum['qq'] = '';
                    }
                    $datum['updated_at'] = $datum['updated_at'] > 0 ? date('Y-m-d H:i:s', $datum['updated_at']) : null;
                    $datum['created_at'] = $datum['created_at'] > 0 ? date('Y-m-d H:i:s', $datum['created_at']) : null;
                    $datum['yy_time'] = $datum['yy_time'] == '0000-00-00 00:00:00' ? null : $datum['yy_time'];
//                    $datum['fb_time'] = ($datum['fb_time'] == '0000-00-00 00:00:00' || $datum['fb_time'] == '') ? null : $datum['fb_time'];
                    $datum['creator_id'] = empty($datum['creator_id']) ? 0 : $datum['creator_id'];
                    $datum['jz_guide_doctor_id'] = empty($datum['jz_guide_doctor_id']) ? 0 : $datum['jz_guide_doctor_id'];
                    $datum['custom_service_id'] = empty($datum['custom_service_id']) ? 0 : $datum['custom_service_id'];
                    $datum['consultation_way_id'] = empty($datum['consultation_way_id']) ? 0 : $datum['consultation_way_id'];
                    $datum['yy_doctor_id'] = empty($datum['yy_doctor_id']) ? 0 : $datum['yy_doctor_id'];
                    if (!empty($datum['disease_data'])) {
                        $diseaseIds = explode(',', $datum['disease_data']);
                        foreach ($diseaseIds as $diseaseId) {
                            $cds[] = [
                                'disease_id' => $diseaseId,
                                'customer_id' => $datum['id'],
                            ];
                        }
                        $datum['disease_data'] = json_encode(Disease::query()->whereIn('id', $diseaseIds)->get(['id', 'name']));
                    } else {
                        $datum['disease_data'] = "{}";
                    }

                    $swt = DB::connection('S')->table('bs_swt_log')->where('booking_id', '=', $datum['id'])->pluck('content');
                    if ($swt->count()) {
                        $datum['swt'] = (empty($datum['swt']) ? "" : $datum['swt']) . implode('', $swt->toArray());
                    }

                    $visit = Visit::query()->where('customer_id', '=', $datum['id'])->orderByDesc('id')->first();
                    if (!empty($visit)) {
                        $datum['last_visit_time'] = $visit['created_at'];
                        $datum['last_visit_user_id'] = $visit['user_id'];
                        if (!empty($datum['hf_time'])) {
                            $visit['next_time'] = $datum['hf_time'];
                            $visit->save();
                        }
                        $datum['visit_data'] = json_encode(Visit::query()
                            ->join('system__users', 'system__users.id', '=', 'ca__visits.user_id')
                            ->where('ca__visits.customer_id', '=', $datum['id'])
                            ->select('ca__visits.id',
                                'ca__visits.content',
                                'ca__visits.user_id',
                                'ca__visits.next_time',
                                'ca__visits.supervisor_annotate',
                                'system__users.name as user_name',
                                'system__users.username as user_username',
                                'system__users.mobile as user_mobile',
                                'ca__visits.created_at'
                            )->get()->toArray());
                    } else {
                        $datum['visit_data'] = "{}";
                        $datum['last_visit_time'] = null;
                        $datum['last_visit_user_id'] = 0;
                    }
                    $addData[] = $datum;
                }
                $cdGs = array_chunk($cds, 1000);
                foreach ($cdGs as $g) {
                    CustomerDisease::query()->insert($g);
                }
                DB::table('ca__customers')->insert($addData);
                $this->count++;
                $this->output->success('success:' . $this->count);
            });
        Visit::query()->join('ca__customers', 'ca__customers.id', '=', 'ca__visits.customer_id')->update(
            [
                'ca__visits.hospital_id' => DB::raw('ca__customers.hospital_id')
            ]
        );
    }
}